package run.bottle.mail.handle;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import run.bottle.mail.model.entity.BaseResponse;
import run.bottle.mail.model.entity.Email;
import run.bottle.mail.model.enums.EmailType;

/**
 * Email handler manager.
 *
 * @author LiYuanCheng
 * @date 2020-06-05 11:49
 * 代码来源：https://github.com/halo-dev/halo/blob/master/src/main/java/run/halo/app/handler/file/FileHandlers.java
 */
@Component
public class EmailHandlers {

  /**
   * Email handler container.
   */
  private final ConcurrentHashMap<EmailType, EmailHandler> emailHandlers = new ConcurrentHashMap<>(16);

  public EmailHandlers(ApplicationContext applicationContext) {
    addEmailHandlers(applicationContext.getBeansOfType(EmailHandler.class).values());
  }

  public void addEmailHandlers(Collection<EmailHandler> emailHandlers){
    if (!CollectionUtils.isEmpty(emailHandlers)) {
      emailHandlers.forEach(emailHandler -> {
        if (this.emailHandlers.containsKey(emailHandler.getEmailType())) {
          throw new RuntimeException("Same attachment type implements must be unique");
        }
        this.emailHandlers.put(emailHandler.getEmailType(), emailHandler);
      });
    }
  }

  public BaseResponse send(Email mail,EmailType emailType){
    return getSupportedType(emailType).send(mail);
  }

  public EmailHandler getSupportedType(EmailType emailType){
    EmailHandler handler = emailHandlers.getOrDefault(emailType, emailHandlers.get(EmailType.TEXT));
      if (handler == null) {
        throw new RuntimeException("No available email handlers to operate the email");
      }
    return handler;
  }
}
